import { Vue } from 'vue-property-decorator';
import ColumnUtil from '../utils/column-util';
import { getUser } from '@/utils/user-util';
import { cancelCommonOrder, trialCalculate } from '@/common/api/instruction';
import { UUID, sortBy } from '@/utils/tools';
import moment from 'moment';
/**
 * 指令下单公共类
 */
export class OrderClass extends Vue {
    ColumnUtil = new ColumnUtil();

    resourceCode: string = ''; // 菜单编码

    instruction: any = {
        orderDirection: 'P',
    }; // 指令对象
    verifyParams: any = {}; // 表单校验字段
    renderCountKey: number = 0; // 表单组件渲染Key

    isUpdate: boolean = false; // 是否是指令修改
    oldOuterOrderCode: string = ''; // 要修改指令的外部指令序号
    serialNo: string = ''; // 要修改指令的流水号

    // 试算结果信息
    trailResultMsg: any = {
        calcTime: '', // 下单/试算时间
        takeTime: '', // 计算耗时
        riskResult: '', // 风控结果
        riskResultTable: [], // 风控结果表数据
    };
    tableKey: number = 0; // 试算结果表key
    calcLoading: boolean = false; // 试算结果表loading
    layoutDialog: boolean = false; // 试算结果表布局设置弹框显示
    tableColumns = this.ColumnUtil.riskTableColumns; // 试算结果表格全部字段
    showFieldList: any[] = []; // 要显示的表格列
    selectedFieldList: any[] = []; // 已选择字段列表
    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '产品代码', id: 'fundCode', sortable: true },
        { content: '产品名称', id: 'fundNameSt', sortable: false },
    ];
    tableName: string = ''; // 布局设置表名
    iconDom: any = null; // 试算结果表筛选图标dom
    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型

    riskOrderResultAfterKey: number = 0; // 指令下达对话框key
    orderCancelShow: boolean = false; // 指令下达对话框

    // 条目组穿梭框
    transDialog: boolean = false;
    // 条目组设置数据
    selectEntryGroupCode = {
        calculateEntryGroup: [], // 计算组
        excludeEntryGroup: [], // 排除组
    };

    /** *********************************** 指令表单相关start ******************************** */

    /**
     * 表单参数为空校验
     * @param instruction 指令表单
     */
    handleVerifyInstructionParam(instruction: any) {
        if (instruction.orderPriceType === '2') {
            delete this.verifyParams.orderPrice;
        }
        for (const key in this.verifyParams) {
            if (!instruction[key]) {
                this.yh_message_warn(this.verifyParams[key] + '不可为空');
                return false;
            }
        }
        return true;
    }

    /**
     * 表单重置事件
     */
    handleClickButtonReset() {
        // this.isUpdate = false;
        // this.renderCountKey++;
        // this.stockInfo = {};
        this.$emit('reset', null);
    }

    /** *********************************** 指令表单相关end ******************************** */

    /** *********************************** 指令试算、下单start ******************************** */
    /**
     * 生成完整的指令表单
     * @param instruction 指令表单
     */
    createInstruction(instruction: any): any {
        // instruction.instructionType = '15';
        // instruction.orderUser = getUser().userCode;
        // instruction.outerOrderCode = UUID() + '-' + new Date().getTime();
        // instruction.requestId = UUID() + '-' + new Date().getTime();
        // if (instruction.orderPriceType === '2') {
        //     instruction.orderPrice = instruction.closePrice;
        // }
        // return instruction;
    }
    /**
     * 指令表单提交事件
     */
    handleFormSubmit(orderType: string) {
        const isUpdate = this.isUpdate;
        // 表单校验
        const verify: any = this.handleVerifyInstructionParam(this.instruction);
        if (!verify) {
            return;
        }

        this.instruction = this.createInstruction(this.instruction);
        this.instruction.orderType = orderType;
        const form: any = {
            orderType: orderType,
            multiType: '2',
            requestId: this.instruction.requestId,
            instructionType: '15',
            outOrderBatchCode: UUID() + new Date().getTime(),
            tradeUser: getUser().userCode,
            calculateEntryGroup: this.selectEntryGroupCode.calculateEntryGroup,
            excludeEntryGroup: this.selectEntryGroupCode.excludeEntryGroup,
            instList: [this.instruction],
        };
        if (orderType == '2') {
            this.instruction.cancelType = '1';
            form.cancelType = '1';
        }
        if (isUpdate) {
            form.excludeSerialNoSet = [this.serialNo];
        }
        const start = window.performance.now();
        this.trailResultMsg.calcTime = moment().format('YYYY-MM-DD HH:mm:ss');
        trialCalculate(form).then((res: any) => {
            const end = window.performance.now();
            this.trailResultMsg.takeTime = ((end - start) / 1000).toFixed(3) + '秒';
            this.trailResultMsg.riskResult = res.thresholdType;
            const data = res.resultList || [];
            // 过滤错误结果,浦银过滤产品不过滤
            // data = data.filter(item => item.thresholdType != '4');
            // data = data.sort(sortBy('thresholdType', 'desc'));
            // this.trailResultMsg.riskResult = data[0]?.thresholdType || res.thresholdType;

            // 根据产品代码 匹配产品名称
            data.forEach(ele => {
                ele.requestId = res.requestId;
                ele.fundNameSt = this.instruction.fundNameSt;
                ele.stockNameSt = this.instruction.stockNameSt;
            });
            this.trailResultMsg.riskResultTable = JSON.parse(JSON.stringify(data));
            if (orderType == '1') {
                this.orderCancelShow = false;
                this.yh_message_success('提交试算信息成功');
            } else {
                if (this.trailResultMsg.riskResult == '0') {
                    this.orderCancelShow = false;
                    this.handleResetResult();
                    const h = this.$createElement;
                    this.$message.success({
                        message: h('p', null, [
                            h('span', null, '本次风控下单结果为'),
                            h('span', { style: 'color: #70b603' }, '"合规"'),
                            h('span', null, '，已下单成功'),
                        ]),
                        showClose: true,
                        customClass: 'messageStyle',
                    });
                    if (isUpdate) {
                        this.handleUpdateCancel();
                    }
                    this.isUpdate = false;
                } else {
                    this.riskOrderResultAfterKey++;
                    this.orderCancelShow = true;
                }
                if (isUpdate) {
                    this.handleUpdateCancel();
                }
            }
            this.$emit('getResult', this.trailResultMsg);
        });
    }

    /**
     * 继续下达按钮点击事件
     */
    riskResultContinue() {
        this.calcLoading = false;
        this.handleResetResult();
        this.$emit('getResult', this.trailResultMsg);
        if (this.isUpdate) {
            this.handleUpdateCancel();
        }
        this.yh_message_success('指令下达成功');
        this.isUpdate = false;
    }

    /**
     * 清空指令试算结果
     */
    handleResetResult() {
        // 重置表单
        this.handleClickButtonReset();
        // 清空试算结果
        this.trailResultMsg = {
            calcTime: '',
            takeTime: '',
            riskResult: '',
            riskResultTable: [],
        };
        //  this.$emit('getResult', this.trailResultMsg);
    }

    /**
     * 修改指令撤单事件
     */
    handleUpdateCancel() {
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.oldOuterOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.oldOuterOrderCode],
        })
            .then(res => {})
            .catch(err => {
                this.yh_message_success(err);
            });
    }

    /**
     * 取消下单按钮点击事件
     */
    riskResultCancel() {
        this.calcLoading = false;
        this.trailResultMsg.riskResultTable = [];
        cancelCommonOrder({
            cancelOrderType: '2',
            tradeUser: getUser().userCode, // 当前用户
            tradeUserName: getUser().userName, // 当前用户
            orderType: '4',
            instructionType: '10',
            instNo: '',
            originOuterOrderCode: this.instruction.outerOrderCode,
            outerOrderCode: UUID() + '-' + new Date().getTime(),
            requestId: UUID() + '-' + new Date().getTime(),
            delOriginOuterOrderCodeList: [this.instruction.outerOrderCode],
        }).then(res => {
            this.yh_message_success('已终止指令下达');
            this.orderCancelShow = false;
        });
    }

    /** *********************************** 指令试算、下单end ******************************** */

    /** *********************************** 条目组设置start ******************************** */
    openEntryGroupDialog() {
        this.transDialog = true;
    }

    getEntryGroup(value: any) {
        this.selectEntryGroupCode.calculateEntryGroup = value.calculateEntryGroup;
        this.selectEntryGroupCode.excludeEntryGroup = value.excludeEntryGroup;
    }

    closeEntryDialog() {
        this.transDialog = false;
        this.getUserSelectEntryGroupList();
    }

    getUserSelectEntryGroupList() {
        this.$axios.get('/entry/group/user/select/list/' + this.resourceCode).then((res: any) => {
            res = res || [];
            const selectEntryGroupCode = {
                calculateEntryGroup: res.filter(item => item.instGroupType === '1' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
                excludeEntryGroup: res.filter(item => item.instGroupType === '2' && item.groupCode !== 'DEFAULT').map(item => item.groupCode),
            };
            this.selectEntryGroupCode.calculateEntryGroup = selectEntryGroupCode.calculateEntryGroup;
            this.selectEntryGroupCode.excludeEntryGroup = selectEntryGroupCode.excludeEntryGroup;
        });
    }

    /** *********************************** 条目组设置end ******************************** */
    /** *********************************** 布局设置start ******************************** */

    filterThresholdType({ value, row, column }) {
        return row.thresholdType == value;
    }

    filterEntryTypeMethod({ value, row, column }) {
        return row.entryType == value;
    }

    // 表格列筛选数据
    filterHandler({ option, row, column }) {
        const property = column['property'];
        return row[property].includes(option.data);
    }

    changeTable() {
        this.$nextTick(() => {
            const icon = [];
            if (!this.iconDom) {
                this.iconDom = document.querySelectorAll('.risk-order-bottom .vxe-icon--funnel');
                this.iconDom.forEach((ele: any, index) => {
                    if (!['风险类型', '阈值类型'].includes(ele.parentNode.parentNode.children[0].innerHTML)) {
                        icon.push(index);
                    }
                });
                for (let i = 0; i < icon.length; i++) {
                    icon.forEach(ele => {
                        if (ele === i) {
                            this.iconDom[i].className = 'vxe-filter--btn el-icon-search';
                        }
                    });
                }
            }
        });
    }

    /**
     * 获取页面布局信息
     */
    async queryLayout(tableName) {
        this.calcLoading = true;
        const resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/' + tableName)
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.calcLoading = false;
        } else {
            this.selectedFieldList = this.tableColumns;
            this.showFieldList = this.tableColumns;
            this.calcLoading = false;
        }
        // 设置筛选、排序条件
        this.showFieldList.forEach((ele: any) => {
            if (['fundCode', 'assetCode', 'fundAccountCode', 'stockCode', 'entryCode'].includes(ele.id)) {
                this.$set(ele, 'sortable', true);
            }
            if (
                [
                    'fundCode',
                    'fundNameSt',
                    'assetCode',
                    'assetName',
                    'fundAccountCode',
                    'fundAccountName',
                    'stockCode',
                    'stockNameSt',
                    'entryCode',
                    'entryName',
                ].includes(ele.id)
            ) {
                this.$set(ele, 'filterMethod', this.filterHandler);
                this.$set(ele, 'filters', [{ data: '' }]);
                this.$set(ele, 'search', true);
            }
            if (ele.id == 'entryType') {
                this.$set(ele, 'filterMethod', this.filterEntryTypeMethod);
                this.$set(ele, 'filters', this.entryTypeArr);
            }
            if (ele.id == 'thresholdType') {
                this.$set(ele, 'filterMethod', this.filterThresholdType);
                this.$set(ele, 'filters', this.ThresholdTypeArr);
            }

            // 重新渲染表格
            this.changeTable();
            this.tableKey++;
        });
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout(this.tableName);
        this.iconDom = null;
        this.changeTable();
        this.tableKey++;
    }

    /** *********************************** 布局设置end ******************************** */
}
